<template>
  <div class="cart-box-body" v-loading.fullscreen.lock="fullscreenLoading">
    <div v-if="goods_list.length">
      <el-table
        ref="multipleTable"
        :data="goods_list"
        tooltip-effect="light"
       
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="46"></el-table-column>
        <!-- @click="jumpDetails(scope.row.id,scope.row.pid,scope.row)" -->
        <el-table-column type="index" width="36" label="序号"></el-table-column>
        <el-table-column label="商品信息" show-overflow-tooltip>
          <template slot-scope="scope">
            <router-link
              class="goods"
              style="color:#333"
              target="_blank"
              :to="{name:'productDetails',params:{id:scope.row.id,pid:scope.row.pid,item:scope.row}, query:{id:scope.row.id,pid:scope.row.pid,item:scope.row}}"
            >
              <div class="commodityDetails">
                <img v-lazyload="scope.row.goods_logo" src="@/assets/logo/loading.png" />
                <!-- <img :src="scope.row.goods_logo"> -->
                <div>
                  <h4>{{scope.row.goods_title}}</h4>
                  <p>商品型号：{{scope.row.goods_spec}}</p>
                  <!-- <p>参 数：{{scope.row.goods_spec}} </p> -->
                </div>
              </div>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="单价(元)" width="200">
          <template slot-scope="scope">
            <div class="unitPrice">￥{{ scope.row.selling_price }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="数量" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input-number
              size="small"
              v-model="scope.row.num"
              @change="handleChange(scope.row.num,scope.row.id)"
              :min="1"
              :max="scope.row.goods_stock"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="小计(元)" width="150">
          <template slot-scope="scope">
            <div class="subtotal">
              ￥
              <span>{{ (scope.row.selling_price * scope.row.num).toFixed(2) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="157" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button size="mini" @click="removeShoppingCart(scope.row.id)">删 除</el-button>
            <el-button size="mini" @click="collection(scope.row.id)">收 藏</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="total">
        <div>
          <el-button @click="allElection(goods_list)" type="primary" size="mini">反 选</el-button>
        </div>
        <div>
          已选
          <span>{{ totalNumber }}</span> 件商品 应付总价 ：
          <span>￥{{ totalPrice | tofixed }}</span>
        </div>
        <div>
          <el-button
            @click="jumpQuotation"
            :type=" this.multipleSelection.length  ? 'primary' : 'info'"
            :disabled="!this.multipleSelection.length > 0 ? true : false "
            :loading="quotationLoading"
          >报价单</el-button>
          <el-button
            @click="jumpSettlement"
            :loading="loading"
            :type=" this.multipleSelection.length  ? 'danger' : 'info'"
            :disabled="!this.multipleSelection.length > 0 ? true : false "
          >去结算</el-button>
        </div>
      </div>
    </div>

    <template v-else>
      <div class="emptyCart">
        <img src="@/assets/images/cartEmpty.png" />
        <i @click="jumpHome">
          购物车还是空的 快去挑两件好货!
          <b>去逛逛 >></b>
        </i>
      </div>
    </template>
  </div>
</template>
<script>
import imgsrc from "../../../assets/images/goods1.png"; // 图片
export default {
  name: "careDetails",

  data() {
    return {
      multipleSelection: [], // 全选
      quotationLoading: false, // 报价单按钮
      loading: false, // 结算按钮
      fullscreenLoading: false,
      goods_list: []
    };
  },

  methods: {
    // 取反
    allElection(rows) {
      console.log(this.multipleSelection);
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    // 全部取消
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 删除 购物车商品
    async removeShoppingCart(id) {
      let user_id = this.$store.state.UserInfor.user_id;
      let product_id = id;
      console.log(user_id, product_id);
      try {
        let DeletedResults = await this.$http({
          method: "post",
          url: `/api/index/web/delToCart`,
          headers: { "X-Requested-With": "XMLHttpRequest" }, // 必须加这个请求头 否则报错：500
          data: {
            user_id,
            product_id
          }
        });
        if (DeletedResults.data.State.Code == 200) {
          this.$notify({
            title: "成功",
            message: "成功从购物车移除了该产品...",
            type: "success"
          });
          this.cartDataInit();
        }
      } catch (error) {
        console.log("除 购物车商品接口出现问题...");
      }
    },
    // 收藏商品
    async collection(id) {
      if (this.$store.state.token) {
        let user_id = this.$store.state.UserInfor.user_id;
        let product_id = id;
        console.log(user_id);
        let res = await this.$http({
          method: "post",
          url: "/api/index/web/addCollection",
          data: {
            user_id,
            product_id
          }
        });
        console.log(res);
        if (res.data.State.Code == 200) {
          this.$notify({
            title: "商品成功加入收藏...",
            type: "success"
          });
        }
        // 判断token是否存在
      } else {
        this.$router.push("/login");
      }
    },
    // 跳转回产品详情页面的方法
    jumpDetails(id, pid, item) {
      console.log(id, pid);
      this.$router.push({
        name: "productDetails",
        params: {
          id,
          pid,
          item
        }
      });
    },
    // 关联商品数据
    async likeInfo(cate_id) {
      let res = await this.$http({
        method: "post",
        url: "/api/index/api/recommendGoods",
        data: {
          cate_id
        }
      });
      if (res.data.State.Code == 200) {
        let lists = res.data.data;
        this.$emit("lists", lists);
      }
    },
    // 获取购物车数据
    async cartDataInit() {
      this.fullscreenLoading = true;
      let user_id = this.$store.state.UserInfor.user_id;
      if (user_id) {
        console.log(user_id);
        try {
          let myCartData = await this.$http({
            method: "post",
            url: `/api/index/web/showCartList`,
            headers: { "X-Requested-With": "XMLHttpRequest" }, // 必须加这个请求头 否则报错：500
            data: {
              user_id
            }
          });
          // 判断购物车是否为空 如果为空的话需要把 遮罩层关掉
          if (this.goods_list) {
            this.fullscreenLoading = false;
          }
          if (myCartData.data.State.Code == 200) {
            this.goods_list = myCartData.data.data;

            let cate_id = this.goods_list[0].cate_id;
            this.likeInfo(cate_id);
          } else if (myCartData.data.State.Code == 2005) {
            this.goods_list = [];
          }
        } catch (error) {
          console.log("获取购物车数据接口出现问题...");
        }
      }
    },
    // 购物车数量点击
    async handleChange(value, id) {
      let user_id = this.$store.state.UserInfor.user_id;
      let num = value;
      let product_id = id;
      console.log(user_id, value, id);
      if (user_id) {
        try {
          let Counter = await this.$http({
            method: "post",
            url: `/api/index/web/productAdd`,
            headers: { "X-Requested-With": "XMLHttpRequest" }, // 必须加这个请求头 否则报错：500
            data: {
              user_id,
              num,
              product_id
            }
          });
          if (Counter.data.State.Code == 200) {
            console.log(Counter);
          }
        } catch (error) {
          console.log("购物车数量点击接口出现问题...");
        }
      }
    },
    // 回到首页
    jumpHome() {
      this.$router.push("/");
    },
    //报价单
    async jumpQuotation() {
      let user_id = this.$store.state.UserInfor.user_id;
      let res = await this.$http({
        method: "post",
        url: "/api/index/api/authUser",
        data: {
          user_id
        }
      });
      if (res.data.State.Code == 200) {
        this.$store.commit("QuotationData", this.multipleSelection);
        this.$router.push("/quotation");
      } else {
        this.$notify.info({
          title: "请到个人中心 完善用户名称 以及账户安全中的邮箱绑定..."
        });
      }
    },
    // 去结算
    async jumpSettlement() {
      this.loading = true;
      let user_id = this.$store.state.UserInfor.user_id;
      let CartArray = [];
      console.log(this.multipleSelection);
      this.$store.commit("SettlementData", this.multipleSelection);
      this.$router.push("/ConfirmOrder");
      this.loading = false;
    }
  },

  filters: {
    tofixed: function(value) {
      let minTotal = 0;
      minTotal = value.toFixed(2);
      return minTotal;
    }
  },

  computed: {
    // 总数量
    totalNumber() {
      let num = 0;
      this.multipleSelection.forEach(element => {
        num += element.num;
      });
      return num;
    },
    // 总价格
    totalPrice() {
      let price = 0;
      this.multipleSelection.forEach(element => {
        price += element.num * element.selling_price;
      });
      return price;
    }
  },

  mounted() {
    this.cartDataInit();
  }
};
</script>
<style lang="scss" scoped>
.cart-box-body {
  /deep/ .el-table {
    .el-table__header-wrapper {
      .el-table__header {
        .has-gutter {
          tr {
            th {
              text-align: center;
              font-weight: bold;
              background: #ebeef5;
            }
          }
        }
      }
    }
    .el-table__body-wrapper {
      .el-table__body {
        .el-table__row {
          .cell {
            .unitPrice {
              width: 100%;
              text-align: center;
            }
            .el-input-number {
              margin-left: 24px;
            }
            .subtotal {
              text-align: center;
              color: #ff1111;
              font-weight: bold;
              span {
                font-size: 18px;
              }
            }
          }
          .commodityDetails {
            display: flex;
            flex-direction: row;
            align-items: center;
            img {
              width: 80px;
              height: 80px;
              margin-left: 10px;
              margin-right: 20px;
            }
            div {
              width: 310px;
              h4 {
                width: 100%;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                margin: 0;
                padding: 0;
              }
              p {
                width: 100%;
                color: #8d8d8d;
                font-size: 12px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                margin: 0;
                padding: 0;
              }
            }
          }
        }
      }
    }
  }

  .total {
    width: 100%;
    height: 68px;
    line-height: 68px;
    background: #ebeef5;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    div {
      &:nth-child(1) {
        margin-left: 44px;
      }
      .el-button {
        margin-right: 10px;
      }
      span {
        color: #ff1111;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
  .emptyCart {
    margin-top: 20px;
    img {
      width: 300px;
    }
    i {
      display: inline-block;
      margin-top: 130px;
      padding-left: 50px;
      font-size: 18px;
      letter-spacing: 2px;
      color: #8d8d8d;
    }
    b {
      color: #ff1111;
      cursor: pointer;
    }
  }
}
</style>


